package com.fanketly.funacg2.ui.viewmodels

import android.util.Log
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.fanketly.funacg2.data.MusicEventListener
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.Children
import com.lzx.starrysky.OnPlayProgressListener
import com.lzx.starrysky.SongInfo
import com.lzx.starrysky.StarrySky
import com.lzx.starrysky.control.RepeatMode.Companion.REPEAT_MODE_NONE
import com.lzx.starrysky.utils.md5
import dagger.hilt.android.lifecycle.HiltViewModel
import java.util.*
import javax.inject.Inject

@HiltViewModel
class MusicViewModel @Inject constructor() : ViewModel() {
    ///////////////////////////////////////////////////////////////////////////
    // 状态区域
    ///////////////////////////////////////////////////////////////////////////
    val _isPlaying by lazy { mutableStateOf(StarrySky.with().isPlaying()) }//是否在播放
    val isPlaying
        get() = _isPlaying.value
    val _audioInfo = mutableStateOf(SongInfo(songName = "当前无播放"))//当前播放音声
    val audioInfo
        get() = _audioInfo.value
    val _audioProcess = mutableStateOf(0)//当前播放音声进度 单位秒
    val audioProcess
        get() = _audioProcess.value
    val _audioAllTime = mutableStateOf(0)//当前播放音声时间
    val audioAllTime
        get() = _audioAllTime.value

    //获取播放模式,默认顺序播放 REPEAT_MODE_NONE 顺序播放 REPEAT_MODE_ONE 单曲播放 REPEAT_MODE_SHUFFLE 随机播放 REPEAT_MODE_REVERSE 倒序播放
    private val _audioRepeatMode by lazy {
        mutableStateOf(StarrySky.with().getRepeatMode().repeatMode)//当前播放模式
    }
    val audioRepeatMode
        get() = _audioRepeatMode.value

    ///////////////////////////////////////////////////////////////////////////
    // 数据区域
    ///////////////////////////////////////////////////////////////////////////
    private var stopTime: Long = 0L//定时的时间
    private var stopStartTime: Long = 0L//定时开始的时间
    private val playList = mutableStateListOf<SongInfo>()//播放列表

    ///////////////////////////////////////////////////////////////////////////
    // 播放列表
    ///////////////////////////////////////////////////////////////////////////
    fun getPlayList() = playList


    fun deletePlayListSong(songInfo: SongInfo) {
        StarrySky.with().removeSongInfo(songInfo.songId)
        playList.remove(songInfo)
//        val remove = StarrySky.with().getPlayList().remove(songInfo)
//        Log.i(TAG, "deletePlayListSong:$remove ")
    }

    fun clearPlayList() {
        StarrySky.with().clearPlayList()
        playList.clear()
    }

    /**
     *@param id 为跳转到详情的id
     * */
    fun playAudioByInfo(id: Int, title: String, url: String, songCover: String) {
        Log.i(TAG, "playAudioByInfo:$url ")
        val songInfo =
            SongInfo(
                songId = url.md5(),
                songName = title,
                songCover = songCover,
                songUrl = url,
                artist = id.toString()
            )
        addToPlayList(songInfo)
        StarrySky.with().playMusicByInfo(songInfo)
    }

    /**
     * list 里的类型一定要是audio，因为前面已经做判断了，所以这里不再做判断
     * @param id 为跳转到详情的id
     * */
    fun addToPlayList(id: Int, thumbnailCoverUrl: String, list: List<Children>) {
        list.forEach {
            val songInfo =
                SongInfo(
                    songId = it.url!!.md5(),
                    songName = it.title,
                    songCover = thumbnailCoverUrl,
                    songUrl = it.url,
                    artist = id.toString()
                )
            addToPlayList(songInfo)
            StarrySky.with().addSongInfo(songInfo)
        }
    }

    /**
     * 用于播放添加到播放列表的音声
     * */
    fun playAudioById(songId: String) {
        Log.i(TAG, "playAudioById: $songId")
        StarrySky.with().playMusicById(songId)
//        setOnPlayProgressListener()
    }

    ///////////////////////////////////////////////////////////////////////////
    // 播放控制
    ///////////////////////////////////////////////////////////////////////////
    fun replay10() {
        StarrySky.with().seekTo(StarrySky.with().getPlayingPosition() - 10000)
    }

    fun previous() {
        if (StarrySky.with().isSkipToPreviousEnabled()) {
            StarrySky.with().skipToPrevious()
        }
    }

    fun seekToFromPercentage(progress: Float, isPlayWhenPaused: Boolean = true) {
        StarrySky.with().seekTo(
            (StarrySky.with().getDuration() * progress).toLong(),
            isPlayWhenPaused = isPlayWhenPaused
        )
    }

    fun seekTo(time: Int, isPlayWhenPaused: Boolean = true) {
        StarrySky.with().seekTo(
            (time * 1000).toLong(),
            isPlayWhenPaused = isPlayWhenPaused
        )
    }

    /**
     *因为添加需要暂停，所以手动修改播放进度
     * */
    fun onlySeekProgress(progress: Float) {
        val p = _audioProcess.value + (audioAllTime * progress).toInt()
        _audioProcess.value = p
        Log.i(TAG, "onlySeekProgress: ${_audioProcess.value}")
//        StarrySky.with().seekTo(p, isPlayWhenPaused = isPlayWhenPaused)
    }

    fun forward30() {
        StarrySky.with().seekTo(StarrySky.with().getPlayingPosition() + 30000)
    }

    fun next() {
        if (StarrySky.with().isSkipToNextEnabled()) {
            StarrySky.with().skipToNext()
        }
    }

    fun pause() = StarrySky
        .with()
        .pauseMusic()

    fun restore() = StarrySky
        .with()
        .restoreMusic()

    fun pauseOrRestoreMusic() {
        if (isPlaying) {
            StarrySky
                .with()
                .pauseMusic()
        } else {
            StarrySky
                .with()
                .restoreMusic()
        }
    }

    /**
     * 设置播放模式 必须是以下之一： REPEAT_MODE_NONE 顺序播放 REPEAT_MODE_ONE 单曲播放 REPEAT_MODE_SHUFFLE 随机播放 REPEAT_MODE_REVERSE 倒序播放
     *  isLoop 播放倒最后一首时是否从第一首开始循环播放,该参数对随机播放无效
     *  REPEAT_MODE_NONE = 100     //顺序播放
     *  REPEAT_MODE_ONE = 200      //单曲播放
     *  REPEAT_MODE_SHUFFLE = 300  //随机播放
     *  REPEAT_MODE_REVERSE = 400  //倒序播放
     * */
    fun changeRepeatMode() {
        val m = if (audioRepeatMode == 300) REPEAT_MODE_NONE else audioRepeatMode + 100
        _audioRepeatMode.value = m
        StarrySky.with().setRepeatMode(m, false)
    }

    /**
     * 定时停止 time 时间，单位毫秒，传 0 为不开启 isPause 到时间了是否暂停，如果为false，则到时间后会调用stop isFinishCurrSong 时间到后是否播放完当前歌曲再停
     * */
    fun setStopTimer(time: Long, isPause: Boolean = false, isFinishCurrSong: Boolean = false) {
        Log.i(TAG, "setStopTimer: $time")
        stopStartTime = Date().time
        stopTime = time
        StarrySky.with().stopByTimedOff(time, isPause, isFinishCurrSong)
    }

    //获取定时停止剩余的时间
    fun getStopRemainingTime(): Long {
        val l = Date().time - stopStartTime//获取的时间-开始的时间
        Log.i(TAG, "getStopRemainingTime(获取的时间-开始的时间): $l")
        val remain = stopTime - l          //剩下多少毫秒
        return if (remain <= 0) 0
        else remain
    }

    private fun addToPlayList(songInfo: SongInfo) {
        if (playList.any { it.songId == songInfo.songId }) return
        playList.add(songInfo)
    }

    fun setOnPlayProgressListener() {
        StarrySky.with().setOnPlayProgressListener(object : OnPlayProgressListener {
            override fun onPlayProgress(currPos: Long, duration: Long) {
                if (currPos < 0) _audioProcess.value = 0
                else _audioProcess.value = (currPos / 1000).toInt()
//                Log.i(TAG, "onPlayProgress: $currPos")
            }
        }, MusicEventListener)
    }

    override fun onCleared() {
        //移除监听
        StarrySky.with().removePlayerEventListener(MusicEventListener)
        StarrySky.with().removeProgressListener(MusicEventListener)
        super.onCleared()
    }
}